Ext.define('YX.core.CodeRule', {
	 extend : 'Ext.panel.Panel',
	 layout : {
	  type : 'hbox',
	  align : 'stretch'
	 },
	 gridRule : null,
	 txtRuleCode : null,
	 txtRuleDesc : null,
	 pelRuleDef : null,
	 gridRuleDtl : null,
	 cmbRuleType : null,
	 txtRuleFixStr : null,
	 cmbRuleDateFormat : null,
	 numRuleSeqInitValue : null,
	 numRuleSeqLength : null,
	 chkRuleSeqCycle : null,
	 rdoRuleSeqYear : null,
	 rdoRuleSeqMonth : null,
	 rdoRuleSeqDay : null,
	 rdoRuleSeqMultRule : null,
	 txtRuleSeqMultRule : null,
	 fsRuleSeq : null,
	 taRuleSql : null,
	 btnGoLeft : null,
	 btnGoRight : null,
	 btnGoUp : null,
	 btnGoDown : null,
	 btnSave : null,
	 btnDelete : null,
	 pelRuleOp : null,
	 initComponent : function() {
	  this.gridRule = Ext.create('Ext.grid.Panel', {
		   title : T.label.ruleList,
		   width : 450,
		   columns : [{
		      text : T.label.ruleCode,
		      dataIndex : 'ruleCode',
		      width : 150
		     }, {
		      text : T.label.ruleDesc,
		      dataIndex : 'ruleDesc',
		      width : 300
		     }],
		   store : Ext.create('Ext.data.JsonStore', {
		      autoLoad : true,
		      fields : ['orgCode', 'ruleCode', 'ruleDesc'],
		      proxy : {
			     type : 'zbusrpc',
			     module : 'BasViewCodeRuleDefinitionService',
			     reader : {
			      root : 'ruleDefList'
			     }
		      }
		     }),
		   listeners : {
		    scope : this,
		    select : this.onGridRuleSelect
		   }
	    });

	  this.txtRuleCode = Ext.create('Ext.form.field.Text', {
		   fieldLabel : T.label.ruleCode,
		   labelWidth : 60,
		   allowBlank : false,
		   maxLength : 30,
		   flex : 2,
		   listeners : {
		    scope : this,
		    blur : this.onTxtRuleCodeBlur
		   }
	    });

	  this.txtRuleDesc = Ext.create('Ext.form.field.Text', {
		   fieldLabel : T.label.ruleDesc,
		   labelWidth : 60,
		   maxLength : 100,
		   flex : 3
	    });

	  this.pelRuleDef = Ext.create('Ext.panel.Panel', {
		   title : T.label.definition,
		   layout : {
		    type : 'hbox',
		    align : 'center'
		   },
		   items : [this.txtRuleCode, this.txtRuleDesc]
	    })

	  this.gridRuleDtl = Ext.create('Ext.grid.Panel', {
		   flex : 1,
		   selModel : Ext.create('Ext.selection.CheckboxModel'),
		   columns : [{
		      text : T.label.sequence,
		      width : 50,
		      dataIndex : 'ruleSeq'
		     }, {
		      text : T.label.ruleType,
		      width : 200,
		      dataIndex : 'ruleType',
		      renderer : function(value) {
			     if (value === 'F') {
			      return T.label.fixedString;
			     } else if (value === 'D') {
			      return T.label.dateTime;
			     } else if (value === 'S') {
			      return T.label.sequence;
			     } else if (value === 'Q') {
			      return T.label.sql;
			     } else {
			      return value;
			     }
		      }
		     }],
		   store : Ext.create('Ext.data.JsonStore', {
		      fields : ['ruleCode', 'ruleSeq', 'ruleType', 'data1', 'data2', 'data3', 'seqCycle', 'accdType', 'codeValue'],
		      proxy : {
			     type : 'zbusrpc',
			     module : 'BasViewCodeRuleDetailService',
			     reader : {
			      root : 'ruleDtlList'
			     }
		      }
		     }),
		   listeners : {
		    scope : this,
		    select : this.onGridRuleDtlSelect,
		    deselect : this.onGridRuleDtlDeselect
		   }
	    });

	  this.cmbRuleType = Ext.create('Ext.form.field.ComboBox', {
		   fieldLabel : T.label.ruleType,
		   style : 'margin-top:5px;',
		   displayField : 'desc',
		   valueField : 'code',
		   editable : false,
		   queryMode : 'local',
		   value : 'F',
		   store : Ext.create('Ext.data.ArrayStore', {
		      fields : ['code', 'desc'],
		      data : [['F', T.label.fixedString], ['D', T.label.dateTime], ['S', T.label.sequence], ['Q', T.label.sql]]
		     }),
		   listeners : {
		    scope : this,
		    select : this.onCmbRuleTypeSelect
		   }
	    });

	  this.txtRuleFixStr = Ext.create('Ext.form.field.Text', {
		   fieldLabel : T.label.fixedString,
		   labelWidth : 60
	    });

	  this.cmbRuleDateFormat = Ext.create('Ext.form.field.ComboBox', {
		   fieldLabel : T.label.format,
		   labelWidth : 60,
		   editable : false,
		   queryMode : 'local',
		   valueField : 'code',
		   displayField : 'code',
		   value : 'yyyy',
		   store : Ext.create('Ext.data.ArrayStore', {
		      fields : ['code'],
		      data : [['yyyy'], ['yyyyMM'], ['yyyyMMdd'], ['yyyyMMddHH'], ['yyyyMMddHHmm'], ['yyyyMMddHHmmss']]
		     })
	    });

	  this.numRuleSeqInitValue = Ext.create('Ext.form.field.Number', {
		   fieldLabel : T.label.initValue,
		   labelWidth : 60,
		   value : 1,
		   maxValue : 999999,
		   minValue : 1
	    });
	  this.numRuleSeqLength = Ext.create('Ext.form.field.Number', {
		   fieldLabel : T.label.length,
		   labelWidth : 60,
		   value : 0,
		   maxValue : 20,
		   minValue : 0
	    });
	  this.chkRuleSeqCycle = Ext.create('Ext.form.field.Checkbox', {
		   fieldLabel : T.label.cycle,
		   labelWidth : 60,
		   listeners : {
		    scope : this,
		    change : this.onChkRuleSeqCycle
		   }
	    });
	  this.rdoRuleSeqYear = Ext.create('Ext.form.field.Radio', {
		   fieldLabel : T.label.year,
		   labelWidth : 60,
		   name : 'accdType'
	    });
	  this.rdoRuleSeqMonth = Ext.create('Ext.form.field.Radio', {
		   fieldLabel : T.label.month,
		   labelWidth : 60,
		   name : 'accdType'
	    });
	  this.rdoRuleSeqDay = Ext.create('Ext.form.field.Radio', {
		   fieldLabel : T.label.day,
		   labelWidth : 60,
		   name : 'accdType'
	    });
	  this.rdoRuleSeqMultRule = Ext.create('Ext.form.field.Radio', {
		   fieldLabel : T.label.multipleRule,
		   labelWidth : 60,
		   name : 'accdType'
	    });
	  this.txtRuleSeqMultRule = Ext.create('Ext.form.field.Text', {
		   fieldLabel : T.label.multipleRule,
		   labelWidth : 60,
		   maxLength : 50
	    });

	  this.taRuleSql = Ext.create('Ext.form.field.TextArea', {
		   maxLength : 100
	    });
	  this.btnGoLeft = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-go-left',
		   scope : this,
		   handler : this.onBtnGoLeftClicked
	    });
	  this.btnGoRight = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-go-right',
		   scope : this,
		   handler : this.onBtnGoRightClicked
	    });
	  this.btnGoUp = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-go-up',
		   scope : this,
		   handler : this.onBtnGoUpClicked
	    });
	  this.btnGoDown = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-go-down',
		   scope : this,
		   handler : this.onBtnGoDownClicked
	    });

	  this.fsRuleSeq = Ext.create('Ext.form.FieldSet', {
		   disabled : true,
		   title : T.label.accordingTo,
		   layout : {
		    type : 'vbox',
		    align : 'stretch'
		   },
		   items : [this.rdoRuleSeqYear, this.rdoRuleSeqMonth, this.rdoRuleSeqDay, this.rdoRuleSeqMultRule,
		     this.txtRuleSeqMultRule]
	    });

	  this.pelRuleOp = Ext.create('Ext.panel.Panel', {
		   flex : 1,
		   layout : 'card',
		   style : 'margin-top:5px;',
		   items : [{
		      layout : {
			     type : 'vbox',
			     align : 'stretch'
		      },
		      items : [this.txtRuleFixStr]
		     }, {
		      layout : {
			     type : 'vbox',
			     align : 'stretch'
		      },
		      items : [this.cmbRuleDateFormat]
		     }, {
		      layout : {
			     type : 'vbox',
			     align : 'stretch'
		      },
		      items : [this.numRuleSeqInitValue, this.numRuleSeqLength, this.chkRuleSeqCycle, this.fsRuleSeq]
		     }, this.taRuleSql]
	    });

	  this.btnSave = Ext.create('Ext.button.Button', {
		   text : T.label.save,
		   itemId : 'btnSave',
		   iconCls : 'icon-save',
		   scope : this,
		   handler : this.onBtnSaveClicked
	    });
	  this.btnDelete = Ext.create('Ext.button.Button', {
		   text : T.label.del,
		   itemId : 'btnDelete',
		   iconCls : 'icon-delete',
		   scope : this,
		   handler : this.onBtnDeleteClicked
	    });

	  this.items = [this.gridRule, {
		   flex : 1,
		   xtype : 'panel',
		   layout : {
		    type : 'vbox',
		    align : 'stretch'
		   },
		   bbar : {
		    items : ['->', this.btnSave, this.btnDelete]
		   },
		   items : [this.pelRuleDef, {
		      title : T.label.operate,
		      flex : 1,
		      xtype : 'panel',
		      layout : {
			     type : 'hbox',
			     align : 'stretch'
		      },
		      items : [this.gridRuleDtl, {
			       xtype : 'toolbar',
			       vertical : true,
			       layout : {
			        layout : 'vbox',
			        pack : 'center'
			       },
			       items : [this.btnGoLeft, this.btnGoRight, this.btnGoUp, this.btnGoDown]
		        }, {
			       xtype : 'panel',
			       flex : 1,
			       layout : {
			        type : 'vbox',
			        align : 'stretch'
			       },
			       items : [this.cmbRuleType, this.pelRuleOp]
		        }]
		     }]
	    }];

	  this.callParent();
	 },
	 onGridRuleSelect : function(sm, record, index) {
	  this.txtRuleCode.setValue(record.get('ruleCode'));
	  this.txtRuleDesc.setValue(record.get('ruleDesc'));
	  this.gridRuleDtl.getStore().load({
		   params : {
		    ruleCode : record.get('ruleCode')
		   }
	    });
	 },
	 onCmbRuleTypeSelect : function(field, records) {
	  this.pelRuleOp.getLayout().setActiveItem(field.getStore().indexOf(records[0]));
	 },
	 onBtnSaveClicked : function(btn) {
	  if (!this.txtRuleCode.isValid() || this.gridRuleDtl.getStore().getCount() == 0) {
		 return;
	  }

	  Ext.Msg.show({
		   title : T.label.del,
		   msg : T.msg.are_you_sure_to_save_data,
		   icon : Ext.Msg.QUESTION,
		   buttons : Ext.Msg.YESNO,
		   scope : this,
		   fn : function(btnId) {
		    if (btnId == 'yes') {
			   btn.disable();
			   this.saveRule(btn);
		    }
		   }
	    });
	 },
	 saveRule : function(btn) {
	  var parm = {
		 ruleCode : this.txtRuleCode.getValue(),
		 ruleDesc : this.txtRuleDesc.getValue(),
		 ruleDtlList : []
	  };

	  this.gridRuleDtl.getStore().each(function(rcd) {
		   parm.ruleDtlList.push(rcd.data);
	    });

	  YX.ZbusRpc.request({
		   module : 'BasSaveCodeRuleService',
		   scope : this,
		   showSuccess : true,
		   params : parm,
		   callback : function() {
		    btn.enable();
		   },
		   success : function() {
		    this.gridRule.getStore().reload();
		   }
	    });
	 },
	 onBtnDeleteClicked : function(btn) {
	  if (Ext.isEmpty(this.gridRule.getSelectionModel().getSelection())) {
		 return;
	  }

	  Ext.Msg.show({
		   title : T.label.del,
		   msg : T.msg.are_you_sure_to_delete_data,
		   icon : Ext.Msg.QUESTION,
		   buttons : Ext.Msg.YESNO,
		   scope : this,
		   fn : function(btnId) {
		    if (btnId == 'yes') {
			   btn.disable();
			   this.deleteRule(btn);
		    }
		   }
	    });
	 },
	 deleteRule : function(btn) {
	  var rcds = this.gridRule.getSelectionModel().getSelection();

	  YX.ZbusRpc.request({
		   module : 'BasDeleteCodeRuleService',
		   scope : this,
		   showSuccess : true,
		   params : {
		    ruleCode : rcds[0].get('ruleCode')
		   },
		   callback : function() {
		    btn.enable();
		   },
		   success : function() {
		    this.gridRule.getStore().reload();
		    this.txtRuleCode.setValue('');
		    this.txtRuleDesc.setValue('');
		    this.gridRuleDtl.getStore().removeAll();
		   }
	    });
	 },
	 onBtnGoLeftClicked : function(btn) {
	  if (!this.txtRuleCode.isValid()) {
		 return;
	  }

	  var rcd = {
		 ruleCode : this.txtRuleCode.getValue(),
		 seqCycle : 'N'
	  };
	  var ruleType = this.cmbRuleType.getValue();
	  rcd.ruleType = ruleType;
	  if (ruleType === 'F') {
		 if (this.txtRuleFixStr.getValue().trim() === '') {
		  return;
		 }
		 rcd.data1 = this.txtRuleFixStr.getValue();
	  } else if (ruleType === 'D') {
		 rcd.data1 = this.cmbRuleDateFormat.getValue();
	  } else if (ruleType === 'S') {
		 rcd.data1 = this.numRuleSeqInitValue.getValue().toString();
		 rcd.data2 = this.numRuleSeqLength.getValue().toString();
		 if (this.chkRuleSeqCycle.getValue()) {
		  rcd.seqCycle = 'Y';
		  if (this.rdoRuleSeqYear.getValue()) {
			 rcd.accdType = 'Y';
		  } else if (this.rdoRuleSeqMonth.getValue()) {
			 rcd.accdType = 'M';
		  } else if (this.rdoRuleSeqDay.getValue()) {
			 rcd.accdType = 'D';
		  } else if (this.rdoRuleSeqMultRule.getValue() && this.txtRuleSeqMultRule.getValue().trim() !== '') {
			 rcd.accdType = 'R';
			 rcd.data3 = this.txtRuleSeqMultRule.getValue().trim();
		  } else {
			 return;
		  }
		 }
	  } else if (ruleType === 'Q') {
		 if (this.taRuleSql.getValue().trim() === '') {
		  return;
		 }
		 rcd.data1 = this.taRuleSql.getValue().trim();
	  } else {
		 return;
	  }
	  this.gridRuleDtl.getStore().add(rcd);
	  this.reSeqRuleDtl();
	 },
	 onBtnGoRightClicked : function(btn) {
	  var rcds = this.gridRuleDtl.getSelectionModel().getSelection();
	  if (!Ext.isEmpty(rcds)) {
		 this.gridRuleDtl.getStore().remove(rcds);
		 this.reSeqRuleDtl();
	  }
	 },
	 onBtnGoUpClicked : function(btn) {
	  var rcds = this.gridRuleDtl.getSelectionModel().getSelection();
	  if (Ext.isEmpty(rcds)) {
		 return;
	  }

	  var index = this.gridRuleDtl.getStore().indexOf(rcds[0]);
	  if (index > 0) {
		 var nRcd = rcds[0].copy();
		 nRcd = this.gridRuleDtl.getStore().insert(index - 1, nRcd);
		 this.gridRuleDtl.getStore().remove(rcds[0]);
		 this.reSeqRuleDtl();
		 this.gridRuleDtl.getSelectionModel().select(nRcd, false, true);
	  }
	 },
	 onBtnGoDownClicked : function(btn) {
	  var rcds = this.gridRuleDtl.getSelectionModel().getSelection();
	  if (Ext.isEmpty(rcds)) {
		 return;
	  }

	  var dtlStore = this.gridRuleDtl.getStore();
	  var index = dtlStore.indexOf(rcds[0]);
	  if (index < dtlStore.getCount() - 1) {
		 var nRcd = rcds[0].copy();
		 nRcd = dtlStore.insert(index + 2, nRcd);
		 dtlStore.remove(rcds[0]);
		 this.reSeqRuleDtl();
		 this.gridRuleDtl.getSelectionModel().select(nRcd, false, true);
	  }
	 },
	 onTxtRuleCodeBlur : function(field) {
	  var ruleCode = this.txtRuleCode.getValue();
	  var dtlStore = this.gridRuleDtl.getStore();
	  dtlStore.each(function(rcd) {
		   if (rcd.get('ruleCode') !== ruleCode) {
		    dtlStore.removeAll();
		    return false;
		   }
	    });
	 },
	 reSeqRuleDtl : function() {
	  var i = 1;
	  this.gridRuleDtl.getStore().each(function(rcd) {
		   rcd.set('ruleSeq', i.toString());
		   i++;
	    });

	 },
	 onGridRuleDtlSelect : function(sm, record) {
	  this.addMultRule();

	  this.cmbRuleType.setValue(record.get('ruleType'));
	  var index = this.cmbRuleType.getStore().findExact('code', record.get('ruleType'));
	  if (index >= 0) {
		 this.pelRuleOp.getLayout().setActiveItem(index);
	  }

	  if (record.get('ruleType') === 'F') {
		 this.txtRuleFixStr.setValue(record.get('data1'));
	  } else if (record.get('ruleType') === 'D') {
		 this.cmbRuleDateFormat.setValue(record.get('data1'));
	  } else if (record.get('ruleType') === 'S') {
		 this.numRuleSeqInitValue.setValue(Ext.Number.from(record.get('data1'), 1));
		 this.numRuleSeqLength.setValue(Ext.Number.from(record.get('data2'), 0));
		 this.rdoRuleSeqYear.setValue(record.get('accdType') === 'Y');
		 this.rdoRuleSeqMonth.setValue(record.get('accdType') === 'M');
		 this.rdoRuleSeqDay.setValue(record.get('accdType') === 'D');
		 if (record.get('accdType') === 'R') {
		  this.rdoRuleSeqMultRule.setValue(true);
		  this.txtRuleSeqMultRule.setText(record.get('data3'));
		 }
	  } else if (record.get('ruleType') === 'Q') {
		 this.taRuleSql.setValue(record.get('data1'));
	  }
	 },
	 onGridRuleDtlDeselect : function(sm, records) {
	  this.addMultRule();
	 },
	 addMultRule : function() {
	  var rcds = this.gridRuleDtl.getSelectionModel().getSelection();

	  var mr = '';
	  if (!Ext.isEmpty(rcds)) {
		 Ext.each(rcds, function(rcd) {
		    if (mr !== '') {
			   mr += '+';
		    }
		    mr += rcd.get('ruleSeq').toString();
		   });
	  }

	  this.txtRuleSeqMultRule.setValue(mr);
	 },
	 onChkRuleSeqCycle : function(field, newValue) {
	  this.fsRuleSeq.setDisabled(!newValue);
	 }
  });